package com.example.serenity.util;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MyUtil {
    public static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static String getRemoteHost(javax.servlet.http.HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
    }

    public static String doGetAsStr(String url) throws Exception {
        // URI m_url = new URI(url);
        // URLDecoder.decode(url,"UTF-8");

        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet(url);

        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            return EntityUtils.toString(httpEntity);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                if (httpResponse != null)
                    httpResponse.close();
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public static Long computationTime(Date startTime, Date endTime){
        try{
            long diff = endTime.getTime()- startTime.getTime();
            return diff/1000;
        }catch(Exception e){
            e.printStackTrace();
            return 61L;
        }
    }

    public static void main(String[] args) {
        try {
           String a = MyUtil.doGetAsStr("http://ip-api.com/json/118.113.9.107?lang=zh-CN");
            System.out.println(a);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
